<?php

class ContributionsController extends AppController {

    public $helpers = array('CustomPagination');
    
    public function beforeFilter() {
        parent::beforeFilter();
        
        $this->layout = "contributions";
        
        $this->validateOrganisationAccount();

        $orgAccount = $this->Session->read('org_account');
        $this->set(compact('orgAccount'));
    }
    
    public function index() {

    }
    
    public function home() {
        $orgAccount = $this->Session->read('org_account');
        $organisation_id = $orgAccount['Organisation']['id'];
        $data = $this->Api->post('/contributions/getOverview', array(
            'organisation_id' => $organisation_id
        ));

        $title_for_layout = date('M, Y').' Contributions Overview';
        $graph_title_bar =  date('M, Y').' Weekly Consolidated';
        $graph_title_pie =  date('M, Y').' Consolidated';
        $this->set(compact('organisation_id','list','title_for_layout','data','graph_title_bar','graph_title_pie'));
    }


    public function settings() {
        $orgAccount = $this->Session->read('org_account');
        $organisation_id = $orgAccount['Organisation']['id'];

        //Contribution Types
        $data_table = $this->Api->post('/contributions/contribution_types', array(
            'organisation_id' => $organisation_id
        ));
        $contribution_type_list = array();
        if( $data_table ) {
            if($data_table['status'] == 'success'){
                $contribution_type_list = $data_table['lists'];
            }
        }

        //Currency
        $data_table = $this->Api->post('/System/getCurrencies', array(
            'organisation_id' => $organisation_id
        ));
        foreach($data_table as $row){
            $currencies_list[$row['Currency']['id']] = $row['Currency']['currency_code'] ." (".$row['Currency']['currency_name'].")";
        }

        $org_meta = $this->Api->post('/System/getDefaultCurrency', array(
            'organisation_id' => $organisation_id
        ));
        $default_currency_value = isset($org_meta['OrganisationSetting']) ? $org_meta['OrganisationSetting']['value']:'';

        //Receipt
        $receipt_settings = $this->Api->post('/System/getReceiptSettings', array(
            'organisation_id' => $organisation_id
        ));
        $receipt_mode_arr = array('manual'=>'Manual','auto'=>'Automatic');


        $title_for_layout = 'Contribution Settings';


        $this->set(compact('organisation_id','title_for_layout','contribution_type_list','default_currency_value','currencies_list','receipt_settings','receipt_mode_arr'));
    }



    public function save_settings($action = '') {
        $orgAccount = $this->Session->read('org_account');
        $organisation_id = $orgAccount['Organisation']['id'];

        //save_default_currency
        if($action == 'save_default_currency') {
            $this->autoRender = false;

            $data = isset($_POST['default_currency']) ? $_POST['default_currency'] : '';

           $response = $this->Api->post('/System/setDefaultCurrency', array(
                'organisation_id' => $organisation_id,
                'default_currency' => $data
            ));

           return json_encode($response);
        }
        //save_receipt_settings
        if($action == 'save_receipt_settings') {
            $this->autoRender = false;

            $receipt_mode = $_POST['receipt_mode'];
            $receipt_prefix = $_POST['receipt_prefix'];
            $receipt_postfix = $_POST['receipt_postfix'];
            $receipt_counter = $_POST['receipt_counter'];

            $response = $this->Api->post('/System/setReceiptSettings', array(
                'organisation_id' => $organisation_id,
                'receipt_mode' => $receipt_mode,
                'receipt_prefix' => $receipt_prefix,
                'receipt_postfix' => $receipt_postfix,
                'receipt_counter' => $receipt_counter
            ));

            return json_encode($response);
        }
    }



    public function contribution_types($action = 'default',$item_id = null) {

        $orgAccount = $this->Session->read('org_account');

        $organisation_id = $orgAccount['Organisation']['id'];


        //add_edit
        if( $action == 'add_edit' ) {
            $this->layout = "ajax";
            $details = array();
            if($item_id != null){
                $data = $this->Api->post('/contributions/contribution_type_detail', array(
                    'organisation_id' => $organisation_id,
                    'module_contribution_type_id' => $item_id
                ));
                if($data['status'] == 'success') {
                    $details = $data['lists'];
                }
            }
            $this->set(compact('details','organisation_id'));

            $this->render('/Contributions/add_edit');
        }

        //save
        if($action == 'save') {
            $this->autoRender = false;

            $data = $_POST;

            $response = $this->Api->post('/contributions/contribution_type_modify', array(
                'organisation_id' => $organisation_id,
                'post' => $data
            ));

            return json_encode($response);
        }

        //delete
        if ($action == 'delete') {
            $this->autoRender = false;

            $result = $this->Api->post('/contributions/contribution_type_delete', array(
                'organisation_id' => $organisation_id,
                'contribution_type_ids' => $_POST['contribution_type_ids']
            ));

            return json_encode($result);
        }

        //details
        if( $action == 'details' ) {
            $this->layout = "ajax";

            $data = $this->Api->post('/contributions/contribution_type_detail', array(
                'organisation_id' => $organisation_id,
                'module_contribution_type_id' => $item_id
            ));

            $details = false;
            if($data['status'] == 'success') {
                $details = $data['lists'];
            }

            $this->set(compact('details'));

            $this->render('/Contributions/contribution_type_detail');
        }

        //fetch
        if( $action == 'fetch' ) {
            $this->autoRender = false;

            $data = $this->Api->post('/contributions/contribution_type_detail', array(
                'organisation_id' => $organisation_id,
                'module_contribution_type_id' => $item_id
            ));

            $details = false;
            if($data['status'] == 'success') {
                $details = $data['lists'];
            }

            return json_encode($details);
        }
    }


    public function collections($action = 'default',$contribution_type_filter = 0){
        $orgAccount = $this->Session->read('org_account');
        $organisation_id = $orgAccount['Organisation']['id'];

        if( $action == 'default' ) {
            $data_table = $this->Api->post('/contributions/contribution_types', array(
                'organisation_id' => $organisation_id
            ));
            $list = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    $list = $data_table['lists'];
                }
            }

            $data_table = $this->Api->post('/contributions/get_payment_types', array(
                'organisation_id' => $organisation_id
            ));
            $payment_types = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    $payment_types = $data_table['lists'];
                }
            }

            $data_table = $this->Api->post('/contributions/collections', array(
                'organisation_id' => $organisation_id,
                'contribution_type_filter'=>$contribution_type_filter,
                'receipt_dt'=>date('Y-m-d')
            ));

            $collection_list = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    foreach($data_table['lists'] as $key => $value){
                        $value['week'] = $this->getWeeks($value['week']);
                        $value['month'] = substr($this->getMonths($value['month']),0,3);
                        $collection_list[] = $value;
                    }
                }
            }

            //Currency
            $currencies_list = array();
            $data_table = $this->Api->post('/System/getCurrencies', array(
                'organisation_id' => $organisation_id
            ));
            foreach($data_table as $row){
                $currencies_list[$row['Currency']['id']] = $row['Currency']['currency_code'];
            }
            $org_meta = $this->Api->post('/System/getDefaultCurrency', array(
                'organisation_id' => $organisation_id
            ));
            $default_currency = isset($org_meta['OrganisationSetting']) ? $org_meta['OrganisationSetting']['value']:'';

            //Receipt
            $receipt_settings = $this->Api->post('/System/getReceiptSettings', array(
                'organisation_id' => $organisation_id
            ));
            $receipt_mode_note = "Manual Receipt Is Active";
            if($receipt_settings['receipt_mode'] == 'auto'){
                $receipt_mode_note = "Automatic Receipt Generation Is Active. ";
            }

            $weeks = $this->getWeeks();
            $cur_week = $this->week_of_month(date('Y-m-d'));
            $months = $this->getMonths();
            $cur_year = date('Y');
            $cur_month = date('n');
            $st_year = $cur_year - 5;
            $years = $this->getYears($st_year,$cur_year);

            $title_for_layout = 'Contributions Collections';
            $this->set(compact('organisation_id','receipt_mode_note','receipt_settings','payment_types','list','collection_list','currencies_list','default_currency','title_for_layout','contribution_type_filter','months','years','weeks','cur_year','cur_month','cur_week'));
        }

        if($action == 'save'){
            $this->autoRender = false;

            $data = json_decode($_POST['data'], true);
            $post = array();
            foreach($data as $key=>$value){
                $post[]= array(
                    'tr_data_id' =>$value['tr_data_id'],
                    'receipt_dt' =>$value['receipt_dt'],
                    'receipt_no' =>$value['receipt_no'],
                    'organisation_account_id' =>$orgAccount['OrganisationAccount']['id'],
                    'organisation_member_id' =>$value['organisation_member_id'],
                    'module_contribution_type_id' =>$value['contributions_type'],
                    'week' =>$value['week_paying'],
                    'month' =>$value['month_paying'],
                    'year' =>$value['year_paying'],
                    'amount' =>$value['amount'],
                    'currency' =>$value['currency'],
                    'module_contribution_payment_type_id' =>$value['payment_type'],
                    'cheque_number' =>$value['cheque_no'],
                );
            }

            $response = $this->Api->post('/contributions/save_contributions', array(
                'organisation_id' => $organisation_id,
                'post_data' => $post
            ));
            return json_encode($response);
        }
    }


    public function members_list() {
        $this->autoRender = false;

        if( isset($_GET['term']) ) {
            $term = $_GET['term'];
            $orgAccount = $this->Session->read('org_account');

            $results = $this->Api->post('/contributions/contacts/search', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'term' => $term,
                'limit' => 10
            ));

            return json_encode($results);
        }
    }



    public function history($action = 'default'){
        $orgAccount = $this->Session->read('org_account');
        $organisation_id = $orgAccount['Organisation']['id'];

        if( $action == 'default' ) {
            $data_table = $this->Api->post('/contributions/contribution_types', array(
                'organisation_id' => $organisation_id
            ));
            $contribution_types = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    $contribution_types = $data_table['lists'];
                }
            }


            $data_table = $this->Api->post('/contributions/get_payment_types', array(
                'organisation_id' => $organisation_id
            ));
            $payment_types = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    $payment_types = $data_table['lists'];
                }
            }

            //Currency
            $currencies_list = array();
            $data_table = $this->Api->post('/System/getCurrencies', array(
                'organisation_id' => $organisation_id
            ));
            foreach($data_table as $row){
                $currencies_list[$row['Currency']['id']] = $row['Currency']['currency_code'];
            }
            $org_meta = $this->Api->post('/System/getDefaultCurrency', array(
                'organisation_id' => $organisation_id
            ));
            $default_currency = isset($org_meta['OrganisationSetting']) ? $org_meta['OrganisationSetting']['value']:'';

            $weeks = $this->getWeeks();
            $months = $this->getMonths();
            $cur_year = date('Y');
            $st_year = $cur_year - 5;
            $years = $this->getYears($st_year,$cur_year);


            $title_for_layout = 'Contributions History';
            $this->set(compact('organisation_id','contribution_types','payment_types','currencies_list','default_currency','title_for_layout','weeks','months','years'));
        }

        if( $action == 'paginate' ) {
            $this->autoRender = false;
            $limit = 10;
            $page = isset($_POST['page']) ? $_POST['page'] : 1;
            $receipt_dt = isset($_POST['query_receipt_dt']) ? $_POST['query_receipt_dt'] : null;
            $receipt_no = isset($_POST['query_receipt_no']) ? $_POST['query_receipt_no'] : null;
            $member_no = isset($_POST['query_member_no']) ? $_POST['query_member_no'] : null;
            $contribution_type = isset($_POST['query_contribution_type']) ? $_POST['query_contribution_type'] : 0;
            $currency = isset($_POST['query_currency']) ? $_POST['query_currency'] : 0;
            $payment_type = isset($_POST['query_payment_type']) ? $_POST['query_payment_type'] : 0;

            $data_table = $this->Api->post('/contributions/history', array(
                'organisation_id' => $organisation_id,
                'page'=>$page,
                'limit'=>$limit,
                'receipt_dt'=>$receipt_dt,
                'receipt_no'=>$receipt_no,
                'member_no'=>$member_no,
                'contribution_type'=>$contribution_type,
                'currency'=>$currency,
                'payment_type'=>$payment_type
            ));

            $total_pages = $data_table['total_pages'];
            $data = $data_table['data'];

            $adjacent = 3; // How many adjacent pages should be shown on each side?
            $months = $this->getMonths();
            $view = new View($this, false);
            $view->set(compact('data','total_pages','limit','page','adjacent','months')); // set variables
            $view->viewPath = 'Elements/contributions/'; // render an element
            $html = $view->render('render_history'); // get the rendered markup


            if($data){
                return json_encode(array('status' => 'success', 'message' =>' Contributions found','data'=>$data, 'render'=>$html));
            }
            else{
                return json_encode(array('status' => 'failed', 'message' => ' Contributions not found'));
            }
        }

        if($action == 'save'){
            $this->autoRender = false;

            $data = json_decode($_POST['data'], true);
            $post = array();
            foreach($data as $key=>$value){
                $post[]= array(
                    'contribution_id' =>$value['contribution_id'],
                    'receipt_id' =>$value['receipt_id'],
                    'receipt_dt' =>$value['receipt_dt'],
                    'receipt_no' =>$value['receipt_no'],
                    'organisation_account_id' =>$orgAccount['OrganisationAccount']['id'],
                    'organisation_member_id' =>$value['organisation_member_id'],
                    'module_contribution_type_id' =>$value['contributions_type'],
                    'week' =>$value['week_paying'],
                    'month' =>$value['month_paying'],
                    'year' =>$value['year_paying'],
                    'amount' =>$value['amount'],
                    'currency' =>$value['currency'],
                    'module_contribution_payment_type_id' =>$value['payment_type'],
                    'cheque_number' =>$value['cheque_no'],
                );
            }


            $response = $this->Api->post('/contributions/update_contributions', array(
                'organisation_id' => $organisation_id,
                'post_data' => $post
            ));
            return json_encode($response);
        }

        if($action == 'delete'){
            $this->autoRender = false;

            $contribution_id = json_decode($_POST['contribution_id'], true);

            $response = $this->Api->post('/contributions/delete_contribution', array(
                'organisation_id' => $organisation_id,
                'contribution_id' => $contribution_id
            ));
            return json_encode($response);
        }
    }


    public function set_receipt_counter() {
        $this->autoRender = false;

        $data = $_POST;
        $receipt_counter = $data['receipt_counter'];

        $orgAccount = $this->Session->read('org_account');

        $results = $this->Api->post('/System/setReceiptCounter', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'receipt_counter' => $receipt_counter
        ));

        return json_encode($results);
    }



    /*
     * Cheque Processing
     */

    public function cheques($action = 'default'){
        $orgAccount = $this->Session->read('org_account');
        $organisation_id = $orgAccount['Organisation']['id'];

        if( $action == 'default' ) {
            $data_table = $this->Api->post('/contributions/contribution_types', array(
                'organisation_id' => $organisation_id
            ));
            $contribution_types = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    $contribution_types = $data_table['lists'];
                }
            }


            $data_table = $this->Api->post('/contributions/get_payment_types', array(
                'organisation_id' => $organisation_id
            ));
            $payment_types = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    $payment_types = $data_table['lists'];
                }
            }

            //Currency
            $currencies_list = array();
            $data_table = $this->Api->post('/System/getCurrencies', array(
                'organisation_id' => $organisation_id
            ));
            foreach($data_table as $row){
                $currencies_list[$row['Currency']['id']] = $row['Currency']['currency_code'];
            }
            $org_meta = $this->Api->post('/System/getDefaultCurrency', array(
                'organisation_id' => $organisation_id
            ));
            $default_currency = isset($org_meta['OrganisationSetting']) ? $org_meta['OrganisationSetting']['value']:'';

            $weeks = $this->getWeeks();
            $months = $this->getMonths();
            $cur_year = date('Y');
            $st_year = $cur_year - 5;
            $years = $this->getYears($st_year,$cur_year);

            $cheque_statuses  = array('Cleared'=>'Cleared', 'Not Cleared'=>'Not Cleared');


            $title_for_layout = 'Cheque Processing';
            $this->set(compact('organisation_id','contribution_types','cheque_statuses','payment_types','currencies_list','default_currency','title_for_layout','weeks','months','years'));
        }

        if( $action == 'paginate' ) {
            $this->autoRender = false;
            $limit = 10;
            $page = isset($_POST['page']) ? $_POST['page'] : 1;
            $receipt_dt = isset($_POST['query_receipt_dt']) ? $_POST['query_receipt_dt'] : null;
            $receipt_no = isset($_POST['query_receipt_no']) ? $_POST['query_receipt_no'] : null;
            $member_no = isset($_POST['query_member_no']) ? $_POST['query_member_no'] : null;
            $contribution_type = isset($_POST['query_contribution_type']) ? $_POST['query_contribution_type'] : 0;
            $currency = isset($_POST['query_currency']) ? $_POST['query_currency'] : 0;
            $payment_type = 2; //Always query cheques
            $cheque_no = isset($_POST['query_cheque_no']) ? $_POST['query_cheque_no'] : null;
            $cheque_status = isset($_POST['query_cheque_status']) ? trim($_POST['query_cheque_status']) : null;

            $data_table = $this->Api->post('/contributions/cheques', array(
                'organisation_id' => $organisation_id,
                'page'=>$page,
                'limit'=>$limit,
                'receipt_dt'=>$receipt_dt,
                'receipt_no'=>$receipt_no,
                'member_no'=>$member_no,
                'contribution_type'=>$contribution_type,
                'currency'=>$currency,
                'payment_type'=>$payment_type,
                'cheque_no'=>$cheque_no,
                'cheque_status'=>$cheque_status,
            ));

            $total_pages = $data_table['total_pages'];
            $data = $data_table['data'];

            $adjacent = 3; // How many adjacent pages should be shown on each side?
            $months = $this->getMonths();
            $view = new View($this, false);
            $view->set(compact('data','total_pages','limit','page','adjacent','months')); // set variables
            $view->viewPath = 'Elements/contributions/'; // render an element
            $html = $view->render('render_cheques'); // get the rendered markup


            if($data){
                return json_encode(array('status' => 'success', 'message' =>' Contributions found','data'=>$data, 'render'=>$html));
            }
            else{
                return json_encode(array('status' => 'failed', 'message' => ' Contributions not found'));
            }
        }

        if($action == 'save'){
            $this->autoRender = false;

            $data = json_decode($_POST['data'], true);

            $response = $this->Api->post('/contributions/cheques_status', array(
                'organisation_id' => $organisation_id,
                'contribution_id' =>$data['contribution_id'],
                'cheque_status' => $data['cheque_status']
            ));
            return json_encode($response);
        }

        if($action == 'delete'){
            $this->autoRender = false;

            $contribution_id = json_decode($_POST['contribution_id'], true);

            $response = $this->Api->post('/contributions/delete_contribution', array(
                'organisation_id' => $organisation_id,
                'contribution_id' => $contribution_id
            ));
            return json_encode($response);
        }
    }



    /*
     * Reporting
     */

    public function report($action = 'default'){
        $orgAccount = $this->Session->read('org_account');
        $organisation_id = $orgAccount['Organisation']['id'];

        if( $action == 'default' ) {
            $data_table = $this->Api->post('/contributions/contribution_types', array(
                'organisation_id' => $organisation_id
            ));
            $contribution_types = array();
            if( $data_table ) {
                if($data_table['status'] == 'success'){
                    $contribution_types = $data_table['lists'];
                }
            }


            //Currency
            $currencies_list = array();
            $data_table = $this->Api->post('/System/getCurrencies', array(
                'organisation_id' => $organisation_id
            ));
            foreach($data_table as $row){
                $currencies_list[$row['Currency']['id']] = $row['Currency']['currency_code'];
            }
            $org_meta = $this->Api->post('/System/getDefaultCurrency', array(
                'organisation_id' => $organisation_id
            ));
            $default_currency = isset($org_meta['OrganisationSetting']) ? $org_meta['OrganisationSetting']['value']:'';

            $weeks = $this->getWeeks();
            $months = $this->getMonths();
            $cur_year = date('Y');
            $st_year = $cur_year - 5;
            $years = $this->getYears($st_year,$cur_year);


            $title_for_layout = 'Contributions Report';
            $this->set(compact('organisation_id','contribution_types','currencies_list','default_currency','title_for_layout','weeks','months','years'));
        }

        if( $action == 'paginate' ) {
            $this->autoRender = false;
            $limit = 10;
            $page = isset($_POST['page']) ? $_POST['page'] : 1;
            $receipt_dt = isset($_POST['query_receipt_dt']) ? $_POST['query_receipt_dt'] : null;
            $receipt_no = isset($_POST['query_receipt_no']) ? $_POST['query_receipt_no'] : null;
            $member_no = isset($_POST['query_member_no']) ? $_POST['query_member_no'] : null;
            $contribution_type = isset($_POST['query_contribution_type']) ? $_POST['query_contribution_type'] : 0;
            $currency = isset($_POST['query_currency']) ? $_POST['query_currency'] : 0;

            $data_table = $this->Api->post('/contributions/history', array(
                'organisation_id' => $organisation_id,
                'page'=>$page,
                'limit'=>$limit,
                'receipt_dt'=>$receipt_dt,
                'receipt_no'=>$receipt_no,
                'member_no'=>$member_no,
                'contribution_type'=>$contribution_type,
                'currency'=>$currency
            ));

            $total_pages = $data_table['total_pages'];
            $data = $data_table['data'];

            $adjacent = 3; // How many adjacent pages should be shown on each side?
            $months = $this->getMonths();
            $view = new View($this, false);
            $view->set(compact('data','total_pages','limit','page','adjacent','months')); // set variables
            $view->viewPath = 'Elements/contributions/'; // render an element
            $html = $view->render('render_history'); // get the rendered markup


            if($data){
                return json_encode(array('status' => 'success', 'message' =>' Contributions found','data'=>$data, 'render'=>$html));
            }
            else{
                return json_encode(array('status' => 'failed', 'message' => ' Contributions not found'));
            }
        }

        if($action == 'save'){
            $this->autoRender = false;

            $data = json_decode($_POST['data'], true);
            $post = array();
            foreach($data as $key=>$value){
                $post[]= array(
                    'contribution_id' =>$value['contribution_id'],
                    'receipt_id' =>$value['receipt_id'],
                    'receipt_dt' =>$value['receipt_dt'],
                    'receipt_no' =>$value['receipt_no'],
                    'organisation_account_id' =>$orgAccount['OrganisationAccount']['id'],
                    'organisation_member_id' =>$value['organisation_member_id'],
                    'module_contribution_type_id' =>$value['contributions_type'],
                    'week' =>$value['week_paying'],
                    'month' =>$value['month_paying'],
                    'year' =>$value['year_paying'],
                    'amount' =>$value['amount'],
                    'currency' =>$value['currency']
                );
            }


            $response = $this->Api->post('/contributions/update_contributions', array(
                'organisation_id' => $organisation_id,
                'post_data' => $post
            ));
            return json_encode($response);
        }

        if($action == 'delete'){
            $this->autoRender = false;

            $contribution_id = json_decode($_POST['contribution_id'], true);

            $response = $this->Api->post('/contributions/delete_contribution', array(
                'organisation_id' => $organisation_id,
                'contribution_id' => $contribution_id
            ));
            return json_encode($response);
        }
    }



}
